home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8924 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.3 KB  |  40 lines

  1. Path: news.microsoft.com!news
  2. From: a-cnadc@microsoft.com (Dann Corbit)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: C unions
  5. Date: 6 Mar 1996 21:47:59 GMT
  6. Organization: Microsoft Corporation
  7. Message-ID: <4hl16f$8al@news.microsoft.com>
  8. References: <367cc$0359.14a@news.express.ca>
  9. NNTP-Posting-Host: 157.57.171.202
  10. Mime-Version: 1.0
  11. X-Newsreader: WinVN 0.93.14
  12.  
  13. In article <367cc$0359.14a@news.express.ca>, gchan@express.ca says...
  14. >
  15. >I need a C union that allows me to freely interpret an integer 
  16. >separately as the least significant byte or the most significant byte, 
  17. >and as a single integer.  
  18. >
  19. >Can someone help me get started on this?
  20. >
  21. This is definitely dependent on the system used. ASSUMING two byte
  22. short, it could look like this:
  23.  
  24. union dirty_trick {
  25.    short sNumber;
  26.    char  cHiLo[2];
  27. };
  28. Which byte will be the most significant depends on 'endianness' of
  29. your machine, implementation of integer, etc.  
  30. And if sNumber can be negative... yuck.  Non-portable & ugly to boot.
  31.  
  32. Why not just {assuming sizeof(sNumber) == 2} :
  33. hi = sNumber/(UCHAR_MAX+1) {don't shift unless you know it is always positive}
  34. lo = sNumber % (UCHAR_MAX+1)
  35. -- 
  36. The opinions expressed in this message are my own personal views
  37. and do not reflect the official views of Microsoft Corporation.
  38. In fact, I'm just a subcontractor, not an employee, so pull in your claws.
  39.  
  40.